package com.ccteam.admin.repositories

import com.ccteam.admin.api.BaseAdminDataSource
import com.ccteam.admin.vo.Resource
import com.ccteam.model.auth.AuthVO
import com.ccteam.model.user.AdminUserDTO
import com.ccteam.network.ApiResult
import com.ccteam.network.ResultVO
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
import javax.inject.Singleton

/**
 * @author Xiaoc
 * @since 2021/4/6
 */
@Singleton
class BaseAdminRepository @Inject constructor(
    private val baseAdminDataSource: BaseAdminDataSource
) {

    /**
     * 管理员登录
     * @param adminName 管理员名称
     * @param adminPassword 管理员登录密码
     */
    suspend fun loginAdmin(adminName: String,adminPassword: String): Resource<AuthVO> {
        return withContext(Dispatchers.IO){
            return@withContext object: BaseSuspendResource<AuthVO, ResultVO<AuthVO>>(){
                override suspend fun handleNetwork(): ApiResult<ResultVO<AuthVO>> {
                    return baseAdminDataSource.loginAdmin(AdminUserDTO(adminName,adminPassword))
                }

                override fun processResponse(response: ApiResult.Success<ResultVO<AuthVO>>): AuthVO {
                    return response.data.data!!
                }

            }.asResource()
        }

    }

    /**
     * 管理员退出登录
     * @param token 管理员Token
     */
    suspend fun logoutAdmin(token: String): Resource<Nothing?> {
        return withContext(Dispatchers.IO){
            return@withContext object: BaseSuspendResource<Nothing?, ResultVO<Nothing>>(){
                override suspend fun handleNetwork(): ApiResult<ResultVO<Nothing>> {
                    return baseAdminDataSource.logoutAdmin(token)
                }

                override fun processResponse(response: ApiResult.Success<ResultVO<Nothing>>): Nothing? {
                    return null
                }

            }.asResource()
        }
    }

    /**
     * 获取RSA公钥
     */
    suspend fun getPublicRSAKey(): Resource<String> {
        return withContext(Dispatchers.IO){
            return@withContext object: BaseSuspendResource<String, ResultVO<String>>(){
                override suspend fun handleNetwork(): ApiResult<ResultVO<String>> {
                    return baseAdminDataSource.getRsaPublicKey()
                }

                override fun processResponse(response: ApiResult.Success<ResultVO<String>>): String {
                    return response.data.data ?: ""
                }

            }.asResource()
        }
    }
}